package com.dmall.play.interview.chapter07;

/**
 * 自顶向下的递归
 * 时间复杂度：O(n^2)
 */
public class Leetcode110V1 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {}

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        } else {
            boolean leftBalance = isBalanced(root.left);
            boolean rightBalance = isBalanced(root.right);
            int leftHeight = height(root.left);
            int rightHeight = height(root.right);

            return leftBalance && rightBalance && Math.abs(leftHeight - rightHeight) <= 1;
        }
    }

    private int height(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int leftHeight = height(node.left);
        int rightHeight = height(node.right);
        return 1 + Math.max(leftHeight, rightHeight);
    }
}
